import api from '@/utils/api.js';
import config from '@/config.js';

export default {
	namespaced: true,
	state() {
		return {
			user: null,
			wechatInfo: null
		}
	},
	mutations: {
		//保存用户
		saveLoginUser(state, user) {
			state.user = user
			uni.setStorageSync('user', user)

		},
		//保存用户
		saveUserWechatInfo(state, info) {
			state.wechatInfo = info
		},
		//退出登录
		logout(state) {
			uni.removeStorageSync('token')
			state.user = {}
		}
	},
	actions: {
		//获取当前用户资料
		async getCurrentUser(context) {
			return await api.get(`/user/info`).then(user => {
				context.commit('saveLoginUser', user)
			}).catch(_ => {
				uni.removeStorageSync('token')
			})
		},
		//保存用户微信信息如Openid/unionid
		//小程序等平台使用
		getUserWechatInfo(context) {
			//#ifdef MP-WEIXIN
			uni.login({
				provider: 'weixin',
				async success(res) {
					const url = `/mini/openid/${config.mini.id}/${res.code}`;
					const response = await api.get(url);
					context.commit('saveUserWechatInfo', response.data)
				}
			})
			//#endif
		},
		//会员登录
		async login(context, payload) {
			await api.post(`/login`, payload).then(async res => {
				uni.setStorageSync('token', res.token)
				context.commit('saveLoginUser', res.data)
			}).catch(() => {
				uni.showToast({
					title: '帐号或密码错误'
				})
			})
		}
	}
}
